var PITCHWISE = PITCHWISE || {};
PITCHWISE.register = PITCHWISE.register || {};

PITCHWISE.register = function (options) {
    'use strict';

    this.authenticated = options.authenticated;
    this.el = {
        'registerForm':$('#registerform'),
        'form':{
            'username':$('#username'),
            'email':$('#email'),
            'password':$('#password'),
            'firstName':$('#first-name'),
            'lastName':$('#last-name')
        }
    };

    console.log('PITCHWISE.register.options', options);
    this.load();
};
PITCHWISE.register.prototype.events = function () {
    var _this = this;

    _this.el.registerForm.on('submit', function (e) {
        var flag = true;

        $('#register-alert').slideUp();

        for (var a in _this.el.form) {
            if (_this.el.form[a].val() == "" && a != 'password') {
                flag = false;
                $('#register-alert').html('Please populate all required fields').slideDown();
                _this.el.form[a].closest('.control-group').removeClass('success').addClass('error');
            } else {
                _this.el.form[a].closest('.control-group').removeClass('error').addClass('success');
            }
        }

        if (flag) {
            var input_data = $(this).serialize();
            console.log(input_data);
            $.ajax({
                type:"POST",
                url:"/ajax/",
                data:input_data,
                success:function (msg) {
                    msg = $.parseJSON( msg );
                    console.log('ajax response',msg);

                    $('#register-alert').html('RESPONSE SUCCESS<br>' + msg.info).slideDown();

                    $('#user_login').val($('#username').val());
                    $('#user_pass').val($('#password').val());
                    $('#loginform').trigger('submit');
                },
                error:function (msg) {
                    console.log(msg);
                    $('#register-alert').html('RESPONSE ERROR<br>' + msg).slideDown();

                }

            });
        }
        return false;
    });


};
PITCHWISE.register.prototype.init = function () {
    if (this.authenticated) {
        window.location.href= "/my-account/";
    }
};

PITCHWISE.register.prototype.load = function () {
    this.events();
    this.init();
};